<?php

namespace addons\qingdongams\model;

use think\Exception;
use think\Model;
use traits\model\SoftDelete;

/**
 *产品库存记录
 */
class PartsStock extends Model
{
    use SoftDelete;

    protected $name = 'qingdongams_parts_stock';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';
    protected $hidden = ['deletetime',  'updatetime'];

    public function parts()
    {
        return $this->hasOne(Parts::class, 'id', 'parts_id')->field('id,name');
    }

    //创建人
    public function createStaff()
    {
        return $this->hasOne(Staff::class, 'id', 'create_staff_id')->field('id,name,img');
    }

    public function getCreatetimeAttr($value)
    {
        return date('Y-m-d H:i', $value);
    }

    //添加库存记录
    public static function addStock($params)
    {

        $model = new self;
        // 调用当前模型对应的User验证器类进行数据验证
        $result = $model->allowField(true)->save($params);
        $lastId = $model->getLastInsID();
        if (false === $result) {
            // 验证失败 输出错误信息
            throw new Exception($model->getError());
        }
        if ($params['type'] == 1) {
            if (Parts::where(['id' => $params['parts_id']])->setInc('stock', $params['number']) == false) {
                throw new Exception('新增库存失败');
            }
        } elseif ($params['type'] == 2) {
            if (Parts::where(['id' => $params['parts_id']])->setDec('stock', $params['number']) == false) {
                throw new Exception('新增库存失败');
            }
        }

        return $lastId;
    }
}
